﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SX.BaseService.API.Base;
using SX.BaseService.Service.Implement.Microservice;
using SX.BaseService.Service.Implement.Microservice.ViewModel;
using SX.BaseService.Service.Interface;
using SX.Core;
using SX.ServiceDiscovery;
using SX.ServiceDiscovery.Abstractions;
using SX.ServiceDiscovery.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;

namespace SX.BaseService.API.Controllers
{

    [Description("服务管理")]
    [Menu]
    public class ServiceController : BaseController
    {
        private readonly IMicroService _service;
        private readonly IServiceDiscovery _serviceDiscovery;
        public ServiceController(IMicroService service, IServiceDiscovery serviceDiscovery )
        {
            _service = service;
            _serviceDiscovery = serviceDiscovery;
        }

        [HttpGet]
        [Description("查询服务")]
        public async Task<IApiResult> QueryServiceList([FromQuery] ServiceQueryModel model)
        {
            var serviceList = new List<ServiceInformation>();
            if (model.Name.IsNull())
            {
                IList<ServiceInformation> tempList = await _serviceDiscovery.FindServiceInstancesAsync();
                serviceList = tempList.ToList();
            }    
            else
            {
                IList<ServiceInformation> tempList = await _serviceDiscovery.FindServiceInstancesAsync(model.Name);
                serviceList = tempList.ToList();
            }
            return ApiResult.Ok(serviceList);

        }

        [HttpPost]
        [Description("服务注册")]
        public async Task<IApiResult> SetServiceInfo([FromBody] SetServiceInfoModel input)
        {
            var info=  await _serviceDiscovery.RegisterServiceAsync(serviceName: input.Name,
                                                         version: input.Version,
                                                         serviceType: EnumHelper.Parse<ServiceType>(input.ServiceType),
                                                         uri: new Uri($"http://{input.HostAndPort.Host}:{input.HostAndPort.Port}"),
                                                         healthCheckUri: new Uri(input.HealthCheckUri),
                                                         tags: input.Tags);
            return ApiResult.Ok(info);
        }

        [HttpPost]
        [Description("服务移除")]
        public async Task<IApiResult> DeleteService([FromBody] List<string> serviceIds)
        {
            foreach(var serviceId in serviceIds)
            {
                await _serviceDiscovery.DeregisterServiceAsync(serviceId);
            }
            return  ApiResult.Ok();
        }

       
    }
}
